const { Order } = require("../models/orderModel");
//获取所有销售订单
async function getSalesOrder(req, res) {

    const { _id, pageSize, currentPage } = req.body;
    // console.log(_id,currentPage,currentPage);
    // 总条数
    // const total = await Order.countDocuments();
    const total = await (await Order.find({ salesId: _id })).length
    // 总页数
    const totalPages = Math.ceil(total / pageSize);
    const data = await Order
        .find({ salesId: _id })
        .limit(pageSize - 0)
        .skip((currentPage - 1) * pageSize)
        .populate("clientId")//关联客户
        .populate("salesId")//关联销售员
    if (data) {
        res.send({
            status: 1,
            data: { total, totalPages, data, pageSize, currentPage },
            message: '获取成功'
        })
    } else {
        res.send({
            status: 0,
            message: '获取失败'
        })
    }
}
//新增订单
async function addOrder(req, res) {
    try {
        // InsuranceTypeId  险种ID
        // clientsId  客户id
        const { name, salesId, clientsId, InsuranceTypeId } = req.body;
        const data = await Order.create({ name, salesId, clientsId, InsuranceTypeId, claim: 0, status: 1 })
        res.send({
            status: 1,
            data,
            message: '新增成功'
        })
    } catch (error) {
        res.send({
            status: 0,
            message: '新增失败',
        })
    }
}
// 删除订单
async function deletOrder(req, res) {
    try {
        const { _id } = req.body;
        const data = await Order.findByIdAndDelete(_id)
        res.send({
            status: 1,
            data,
            message: '删除订单成功'
        })
    } catch (error) {
        res.send({
            status: 0,
            message: '删除订单失败'
        })
    }
}
// 获取一个订单
async function getOrder(req, res) {
    try {
        const { _id } = req.body;
        const data = await Order.findById(_id)
        res.send({
            status: 1,
            data,
            message: '获取订单成功'
        })
    } catch (error) {
        res.send({
            status: 0,
            message: '获取订单失败'
        })
    }
}
//修改订单
async function updateOrderSuccess(req,res){
    try {
        const { _id, name, type, time, status } = req.body;
        const data = await Order.updateOne({ _id }, { name, type, time, status  })
        res.send({
            status: 1,
            data,
            message: '修改订单成功'
        })
    } catch (error) {
        res.send({
            status: 0,
            data,
            message: '修改订单失败'
        })
    }
}
module.exports = { getSalesOrder, addOrder, deletOrder, getOrder ,updateOrderSuccess}
